#include "dbuse.h"

dbuse::dbuse()
{
    //dbName = "dbDefault";
    tableName = "tableDefault";
    isConnected = false;
}

//dbuse::dbuse(QString _dbName, QString _tableName)
//{
//    dbName = _dbName;
//    tableName = _tableName;
//    isConnected = false;
//}

//void dbuse::setDBName(QString _dbName)
//{
//    dbName = _dbName;
//}

//void dbuse::setTableName(QString _tableName)
//{
//    tableName = _tableName;
//}

bool dbuse::dbConnect(QString dbName)
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbName);
    if (!db.open())
    {
        error = db.lastError();
        return false;
    }
    isConnected = true;
    return true;
}

//bool dbuse::dbCreate()
//{

//}

bool dbuse::dbTableCreate()
{
    QSqlQuery query;
    QString str = "CREATE TABLE " + tableName + "( "
                      "AuthorNames VARCHAR(200), "
                      "JournalName VARCHAR(200), "
                      "JournalInfo VARCHAR(50), "
                      "ArticleName VARCHAR(250), "
                      "Annotation VARCHAR(400), "
                      "FullText VARCHAR(500), "
                      "ArticleURL VARCHAR(100)"
                      ");";
    if (!query.exec(str))
    {
        error = query.lastError();
        return false;
    }
    return true;
}

bool dbuse::dbExec(QString param)
{
    QSqlQuery query;
    if (!query.exec(param))
    {
        error = query.lastError();
        return false;
    }
    return true;
}

bool dbuse::dbInsert(ArticleStruct ArtStrct)
{
    QSqlQuery query;
    QString strF =
            "INSERT INTO " + tableName +
            " (AuthorNames, JournalName, JournalInfo, ArticleName, Annotation, FullText, ArticleURL)"
            "VALUES('%1', '%2', '%3', '%4', '%5', '%6', '%7' )";


    QString ANames = " ";
    QString Ann = " ";
    foreach (QString _Ann, ArtStrct.Annotations)
    {
        Ann += _Ann;
    }
    if (!Ann.trimmed().isEmpty())
    {
        foreach (QString Auth, ArtStrct.AuthorNames)
        {
            ANames += Auth + ", ";
        }
        QString str = strF.arg(ANames)
                  .arg(ArtStrct.JournalName)
                  .arg(ArtStrct.JournalInfo)
                  .arg(ArtStrct.ArticleName)
                  .arg(ArtStrct.Annotations[0])
                  .arg(ArtStrct.FullText)
                  .arg(ArtStrct.ArticleUrl.toString());
        if (!query.exec(str))
        {
            error = query.lastError();
            return false;
        }
    }
    return true;
}

void dbuse::dbClose()
{
    db.close();
    isConnected = false;
}

//bool dbuse::dbShow()
//{

//}

void dbuse::getModel(QSqlTableModel *model, QString param)
{
    model->setTable(tableName);
    model->setFilter(param);
    model->select();
}
